class Admin::RanksController < Admin::AdminController
  skip_before_action :store_previous_url

  def create
    if params[:multi]
      create_ranks
    else
      product = Product.find(params[:rank][:product_id])
      product.update(status: :approved)
      @rank = Rank.new(rank_params)
      @rank.save!
      redirect_to redirect_back_or_default(admin_innoaward_products_path(product.innoaward))
    end
  end

  def create_ranks
    params[:rank][:award_ids].each do |award_id|
      unless award_id.empty?
        award = Award.find(award_id)
        product = Product.find(params[:rank][:product_id])
        unless award.products.include?(product)
          product.update(status: :approved)
          rank = Rank.new({product_id: params[:rank][:product_id], award_id: award_id})
          rank.save!
        end
      end
    end
    redirect_back_or_default(root_path)
  end

  def update
    @rank = Rank.find(params[:id])
    if @rank.update(rank_params)
      render json: {success: 'success'}
    else
      render json: {error: 'error'}
    end
  end

  def destroy
    @rank = Rank.find(params[:id])
    @rank.destroy
    redirect_to "#{ranks_admin_innoaward_path(@rank.innoaward.id)}?award_id=#{@rank.award.id}"
  end

  private
  def rank_params
    params.require(:rank).permit(:product_id, :award_id, :order)
  end
end
